package com.deyuanyun.pic.web.controller;

import com.deyuanyun.pic.cache.SessionCacheSupport2;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.controller.dto.UserSessionVO;
import com.deyuanyun.pic.domain.prvlg.CustomUser;
import com.deyuanyun.pic.domain.prvlg.Menu;
import com.deyuanyun.pic.pipe.controller.PipeBaseController;
import com.deyuanyun.pic.service.prvlg.UserService;
import com.deyuanyun.pic.web.utils.SecurityUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xu on 2016/1/20.
 */
@Controller
public class IndexPage extends PipeBaseController{
    static Logger logger=Logger.getLogger(IndexPage.class);

    @RequestMapping("login.json")
    @ResponseBody
    public void login(String userName, String pwd, HttpServletRequest request){
        Asserts.assertTrue(StringUtils.isNotBlank(userName),"帐户名不能为空");
        Asserts.assertTrue(StringUtils.isNotBlank(pwd),"密码不能为空");
        userName=userName.trim();
        pwd=pwd.trim();
        UserService userService = SpringAppliction.getBean(UserService.class);
        List<CustomUser> userList = userService.getUser(userName);
        Asserts.assertTrue(ObjectUtil.isNotNullEmpty(userList),"用户不存在");
        Asserts.assertTrue(userList.size()==1,"用户数量错误！");
        CustomUser user=userList.get(0);
        userName=user.getUsername();
        Asserts.assertTrue(StringUtils.isNotBlank(userName),"用户名怎么可能是空的?");
        Subject suser = org.apache.shiro.SecurityUtils.getSubject();
        String enPwd = SecurityUtils.encodePassword(userName, pwd);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, enPwd);
        try {
            suser.login(token);
        } catch (DisabledAccountException e1){
            Asserts.assertTrue(false,"帐户已经被禁用");
            org.apache.shiro.SecurityUtils.getSubject().logout();
            return ;
        }catch (AuthenticationException e) {
            Asserts.assertTrue(false,"用户名或密码错误!");
            org.apache.shiro.SecurityUtils.getSubject().logout();
            return ;
        }
        UserSessionVO sessionVO= SessionCacheSupport2.getSessionVO();
        List<Menu> menuList=sessionVO.getMenuList();
        Set<String> strings1=new HashSet<String>();
        if (ObjectUtil.isNotNullEmpty(menuList)){
            for (Menu menu:menuList){
                strings1.add(menu.getCode());
            }
        }
        sessionVO.setMenuString(StringUtils.join(strings1,",").replace("admin:manage",""));
        request.getSession().setAttribute("username", userName);

        AjaxSupport.sendSuccessText("success","loginSuccess");
        return;
    }

    @RequestMapping("/loginout.html")
    public void loginout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        SecurityUtils.removeUser(request);
        org.apache.shiro.SecurityUtils.getSubject().logout();
        response.sendRedirect("index.html");
        // return new ModelAndView("redirect:login.html");
    }

    @RequestMapping("/index.html")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //String x= new String(ApplicationConfigUtil.getConfigByName("company_name").getBytes("ISO-8859-1"),"gbk") ;
        return forword("index");
        //response.sendRedirect("index.jsp");
        // return new ModelAndView("redirect:login.html");

    }
}
